package com.controller;

import com.bean.Order;
import com.common.Result;
import com.service.OrderService;
import com.utils.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 根据订单 ID 获取订单信息
     * @param orderId 订单的唯一标识
     * @return 封装了订单信息的结果对象
     */
    @GetMapping("/{orderId}")
    public Result<Order> getOrderById(@PathVariable Integer orderId) {
        Order order = orderService.getOrderById(orderId);
        if (order != null) {
            return Result.success(order);
        } else {
            return Result.fail("订单不存在");
        }
    }

    /**
     * 分页模糊查询用户的订单信息
     * @param userId 用户的唯一标识
     * @param keyword 模糊查询关键字，可匹配订单状态
     * @param pageNum 当前页码
     * @param pageSize 每页记录数
     * @return 封装了分页订单信息的结果对象
     */
    @GetMapping("/user/{userId}")
    public Result<PageInfo<Order>> getOrdersByUserIdWithKeyword(@PathVariable Integer userId,
                                                                @RequestParam(required = false) String keyword,
                                                                @RequestParam(defaultValue = "1") int pageNum,
                                                                @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<Order> pageInfo = orderService.getOrdersByUserIdWithKeyword(userId, keyword, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 插入新的订单信息
     * @param order 订单对象
     * @return 封装了插入结果的结果对象
     */
    @PostMapping
    public Result<Boolean> insertOrder(@RequestBody Order order) {
        boolean result = orderService.insertOrder(order);
        if (result) {
            return Result.success(true);
        } else {
            return Result.fail("插入订单失败");
        }
    }

    /**
     * 根据订单 ID 更新订单信息
     * @param order 订单对象
     * @return 封装了更新结果的结果对象
     */
    @PutMapping
    public Result<Boolean> updateOrder(@RequestBody Order order) {
        boolean result = orderService.updateOrder(order);
        if (result) {
            return Result.success(true);
        } else {
            return Result.fail("更新订单失败，订单可能不存在");
        }
    }

    /**
     * 根据订单 ID 删除订单信息
     * @param orderId 订单的唯一标识
     * @return 封装了删除结果的结果对象
     */
    @DeleteMapping("/{orderId}")
    public Result<Boolean> deleteOrderById(@PathVariable Integer orderId) {
        boolean result = orderService.deleteOrderById(orderId);
        if (result) {
            return Result.success(true);
        } else {
            return Result.fail("删除订单失败，订单可能不存在");
        }
    }
}